package com.example.myapplication.fragment

import android.os.Build
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.fragment.app.FragmentActivity
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.Observer
import androidx.lifecycle.lifecycleScope
import androidx.navigation.NavOptions
import androidx.navigation.fragment.FragmentNavigatorExtras
import androidx.navigation.fragment.findNavController
import com.drake.brv.utils.models
import com.example.myapplication.MainViewModel
import com.example.myapplication.R
import com.example.myapplication.databinding.FragmentAddRewardBinding
import com.example.myapplication.databinding.FragmentHomeBinding
import com.example.myapplication.db.Reward
import com.example.myapplication.db.User
import com.example.myapplication.type.SortOrder
import com.example.myapplication.type.SortType
import com.example.myapplication.utils.DivisionString
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.time.LocalDateTime

class AddRewardFragment : BaseFragment<FragmentAddRewardBinding>() {
    private val mViewModel: MainViewModel by activityViewModels()
    lateinit var thisAccount: String
    override fun initBinding(): FragmentAddRewardBinding {
        return FragmentAddRewardBinding.inflate(layoutInflater)
    }

    @RequiresApi(Build.VERSION_CODES.O)
    override fun initView() {

        mViewModel.loggedInUser.observe(viewLifecycleOwner, Observer {Logged_user ->
            thisAccount=Logged_user
        })
        mBinding.comeBack.setOnClickListener {
            findNavController().popBackStack()

        }
        mBinding.btnSubmit.setOnClickListener {
            val title = mBinding.etTitle.text.toString()
            val price = mBinding.etRewardPrice.text.toString()
            val description = mBinding.etRewardDescription.text.toString()

            if (price.isBlank()) {
                Toast.makeText(requireContext(), "来个你合适的价位", Toast.LENGTH_SHORT).show()
            } else if (description.isBlank()) {
                Toast.makeText(requireContext(), "来些有效的介绍", Toast.LENGTH_SHORT).show()
            } else if (title.isBlank()) {
                Toast.makeText(requireContext(), "做个鹤立鸡群的标题！", Toast.LENGTH_SHORT).show()
            } else {
                // 记录当前时间
                val currentTime = thisTime()

                // 创建悬赏对象
                val reward = Reward(
                    account = thisAccount,
                    title = title,
                    time = currentTime,
                    price = price.toDouble(),
                    content = description,
                    comment = "",
                    hasGone = false, // 初始状态为未完成,,
                    rewardApplyAccountList = "",
                    isEnd = false
                )

                // 将悬赏数据转换为 JSON
                val divisionString = DivisionString()

                // 使用协程在后台线程中保存数据
                lifecycleScope.launch(Dispatchers.IO) {
                    // 查询当前用户
                    val user = mViewModel.findUserByAccount(thisAccount)

                    user?.let {
                        // 判断当前悬赏是否为空
                        val currentRewardList = mutableListOf<Reward>()
                        if(user.reward!=""){
                            divisionString.parseAwardString(user.reward)?.forEach{
                                currentRewardList.add(it)
                            }
                        }
                        // 将新的悬赏添加到列表中
                        currentRewardList.add(reward)

                        // 将整个悬赏列表转换为 JSON
                        val updatedRewardJson = divisionString.convertToJson(currentRewardList)

                        // 更新用户的悬赏数据
                        user.reward = updatedRewardJson

                        // 更新数据库
                        mViewModel.updateUser(user)

                        // 回到主线程，显示成功提示
                        withContext(Dispatchers.Main) {
                            Toast.makeText(requireContext(), "成功添加悬赏！", Toast.LENGTH_SHORT).show()
                            findNavController().popBackStack()
                        }
                    }
                }

            }
        }

    }
    @RequiresApi(Build.VERSION_CODES.O)
    private fun thisTime(): String {
        val current = LocalDateTime.now()
        val year = current.year.toString().padStart(4, '0')
        val month = current.monthValue.toString().padStart(2, '0') // 获取当前月，确保两位
        val day = current.dayOfMonth.toString().padStart(2, '0')   // 获取当前日，确保两位
        val hour = current.hour.toString().padStart(2, '0')        // 获取当前小时，确保两位
        val minute = current.minute.toString().padStart(2, '0')    // 获取当前分钟，确保两位
        return year + month + day + hour + minute
    }

}